package io.gitee.devaper.starlight.autoconfigure.interceptor

import org.springframework.aop.support.AopUtils
import org.springframework.beans.factory.*
import org.springframework.context.*
import org.springframework.context.annotation.Configuration
import org.springframework.util.Assert
import org.springframework.web.servlet.HandlerInterceptor
import org.springframework.web.servlet.config.annotation.*

/**
 * WebMVC拦截器自动配置, 主要将[WebInterceptor]注解标记的类自动注册为拦截器
 */
@Configuration(proxyBeanMethods = false)
open class WebInterceptorAutoConfiguration : WebMvcConfigurer, ApplicationContextAware {
    override fun addInterceptors(registry: InterceptorRegistry) {
        applicationContext.getBeansWithAnnotation<WebInterceptor>().values.forEach { bean ->
            Assert.isInstanceOf(HandlerInterceptor::class.java, bean)

            val annotation = AopUtils.getTargetClass(bean).getAnnotation(WebInterceptor::class.java)

            registry.addInterceptor(bean as HandlerInterceptor).apply {
                if (annotation.include.isNotEmpty()) {
                    addPathPatterns(*annotation.include)
                }
                if (annotation.exclude.isNotEmpty()) {
                    excludePathPatterns(*annotation.exclude)
                }
                order(annotation.order)
            }
        }
    }

    private lateinit var applicationContext: ApplicationContext

    override fun setApplicationContext(applicationContext: ApplicationContext) {
        this.applicationContext = applicationContext
    }
}